﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Kenly.ChineseSegment.Core
{
    /// <summary>
    /// 统计分词出现次数。
    /// </summary>
    public class SegmentStatistic
    {
        /// <summary>
        /// 统计分词出现次数。
        /// </summary>
        /// <param name="text"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public static List<SegmentCountPair> Count(string text,params string[] separator)
        {
            if(string.IsNullOrEmpty(text))
            {
                return new List<SegmentCountPair>();
            }

            if (separator == null || separator.Length <= 0)
            {
                separator=new string[]{"/"};
            }

            //切分文本
            string[] segments = text.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            //统计分词出现次数
            Dictionary<string, int> countDict = new Dictionary<string, int>();
            AddToDictionary(segments, countDict);

            //统计结果存储于链表
            List<SegmentCountPair> segmentCountPairs = new List<SegmentCountPair>();
            foreach (string key in countDict.Keys)
            {
                SegmentCountPair segmentCountPair=new SegmentCountPair();
                segmentCountPair.Segment=key;
                segmentCountPair.Count = countDict[key];

                segmentCountPairs.Add(segmentCountPair);
                segmentCountPair.DefaultIndex = segmentCountPairs.IndexOf(segmentCountPair);
            }

            //降序
            segmentCountPairs.Sort(new SegmentCountComparer(false));

            return segmentCountPairs;
        }

        private static void AddToDictionary(string[] segments, Dictionary<string, int> countDict)
        {
            foreach (string segment in segments)
            {
                if (segment.Length < 2)
                {
                    continue;
                }

                if (countDict.ContainsKey(segment))
                {
                    countDict[segment] += 1;
                }
                else
                {
                    countDict.Add(segment, 1);
                }
            }
        }
    }
}
